package trystero.lib.http.se;

import java.net.URL;
import java.net.HttpURLConnection;
import java.net.URLEncoder;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Vector;

import trystero.lib.http.POSTData;
import trystero.lib.http.HTTPRequestState;
import trystero.lib.http.HTTPClient;
import trystero.lib.http.Cookie;

public class HTTPClientImpl extends HTTPClient
{
   public InputStream get(HTTPRequestState state) throws Exception
   {
      URL url = new URL(state.url());

      HttpURLConnection connection = (HttpURLConnection)url.openConnection();

      if(state.cookie() != null)
         connection.setRequestProperty("Cookie", adapt(state.cookie()));

      connection.connect();
      int code = connection.getResponseCode();

      InputStream input = connection.getInputStream();
      return input;
   }

   public InputStream post(HTTPRequestState state) throws Exception
   {
      URL url = new URL(state.url());

      HttpURLConnection connection = (HttpURLConnection)url.openConnection();
      connection.setRequestMethod("POST");
      connection.setRequestProperty("Content-Type", 
	 "application/x-www-form-urlencoded");

      if(state.cookie() != null)
         connection.setRequestProperty("Cookie", adapt(state.cookie()));

      connection.setDoInput(true);
      connection.setDoOutput(true);

      OutputStream output = connection.getOutputStream();

      OutputStreamWriter writer = new OutputStreamWriter(output);
      writer.write(state.data().toString(), 0, state.data().toString().length());
      writer.flush();
      writer.close();

      int code = connection.getResponseCode();

      InputStream input = connection.getInputStream();
      return input;
   }

   private String adapt(Cookie cookie)
   {
      String data = "";
      data += URLEncoder.encode(cookie.key()) + "=" + URLEncoder.encode(cookie.value()) + "; ";
      data += URLEncoder.encode("domain") + "=" + URLEncoder.encode(cookie.domain());
      data += URLEncoder.encode("path") + "=" + URLEncoder.encode(cookie.path());

      return data;
   }
}
